//
//  CYDXVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/21.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYDXVC.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYHttpTool.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "UIImageView+WebCache.h"
#import "GCD.h"
#import "MBProgressHUD+LE.h"
#import "CYJsonInfo.h"
#include <JavaScriptCore/JavaScriptCore.h>
#include <JavaScriptCore/JSStringRefCF.h>
#import "WebViewJavascriptBridge.h"
#import "NSDictionary+JKJSONString.h"
#import "NSString+JKDictionaryValue.h"
#import "CYTool.h"
#import "LEBarButtonItem.h"


@interface CYDXVC ()<UIWebViewDelegate>
@property(nonatomic, strong) GCDTimer *GCDTimer;
@property (weak, nonatomic) IBOutlet UILabel *phonetypeLab;
@property (weak, nonatomic) IBOutlet UITextField *dealcodeTF;
@property (weak, nonatomic) IBOutlet UITextField *imagedealcodeTF;
@property (weak, nonatomic) IBOutlet UIButton *imagedealcodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *yanzhengbtn;
@property (weak, nonatomic) IBOutlet UIImageView *dealcodeimageView;
@property (nonatomic, strong) NSString *mnoCertification;
@property (nonatomic, strong) NSString *AreaCode;
@property (nonatomic, strong) NSString *CityNo;
@property (nonatomic, strong) NSString *ProvinceID;
@property WebViewJavascriptBridge* bridge;

@property (nonatomic, strong) UIWebView *webview;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (nonatomic, strong) NSString *longstr;



@end

@implementation CYDXVC

- (void)viewDidLoad {
    [super viewDidLoad];
     _webview=[[UIWebView alloc]initWithFrame:CGRectZero];
     NSString *filePath=[[NSBundle mainBundle]pathForResource:@"189password" ofType:@"html"];
     NSString *baseURL=[[NSBundle mainBundle]resourcePath];
     NSString *htmlString=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
     
     [_webview setDelegate:self];
     _webview.backgroundColor=[UIColor blackColor];
     [_webview loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:baseURL]];
     
     
     
     
     
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(submitclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"确定" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;
    // Do any additional setup after loading the view from its nib.
     
     
     [self itemview];
}

-(void)itemview{
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(xuanze) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"选择" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.leftBarButtonItem= rightItem;
     
}

-(void)xuanze{
     //重新赋值新的item
     LEBarButtonItem *submit = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_fb"] andSelImage:nil andTitle:@"删除" target:self action:@selector(shanchu)];
     //     self.navigationItem.rightBarButtonItem = submit;
     LEBarButtonItem *help = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_bzpng"] andSelImage:nil andTitle:@"暂停" target:self action:@selector(zanting)];
     
      LEBarButtonItem *quxiao = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_bzpng"] andSelImage:nil andTitle:@"取消" target:self action:@selector(quxiao)];
     
     
     [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects: help,submit,quxiao,nil]];
     
     
}
-(void)quxiao{
     //触发取消
     CYAlertView(@"触发取消");
     [self.navigationItem setLeftBarButtonItems:nil];
     [self itemview];
     
     
}
-(void)shanchu{
     //回到默认选择
     CYAlertView(@"触发删除");
     
}
-(void)zanting{
     CYAlertView(@"触发暂停");
     
}


-(void)loadstatues{
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请输入手机号");
          return;
     }
     NSDictionary *param = @{@"m":@"checkphone",@"phone":_phoneTF.text};
     
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://login.189.cn/login/ajax"]];
     NSString *post =  [self createPostBody:param];
     NSLog(@"post = %@",post);
     
     [request setHTTPMethod:@"POST"];
     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
     [request setHTTPBody:postData];
     [request setTimeoutInterval:60.0];
     
     
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
          NSString *jsonstr = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
          NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
          _AreaCode = [dic objectForKey:@"AreaCode"];
          _CityNo = [dic objectForKey:@"CityNo"];
          _ProvinceID = [dic objectForKey:@"ProvinceID"];
          
          
          if (_AreaCode&&_CityNo&&_ProvinceID) {
               NSDictionary *param = @{@"m":@"loadlogincaptcha",@"Account":_phoneTF.text,@"UType":@"201",@"ProvinceID":_ProvinceID,@"AreaCode":_AreaCode,@"CityNo":_CityNo};
               
               NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://login.189.cn/login/ajax"]];
               NSString *post =  [self createPostBody:param];
               NSLog(@"post = %@",post);
               
               [request setHTTPMethod:@"POST"];
               NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
               [request setHTTPBody:postData];
               [request setTimeoutInterval:60.0];
               
               [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                    
                    NSString *needjsonstr = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
                    NSLog(@"jsonstr = %@",needjsonstr);
                    NSData *jsonData = [needjsonstr dataUsingEncoding:NSUTF8StringEncoding];
                    NSError *err;
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                        options:NSJSONReadingMutableContainers
                                                                          error:&err];
                    NSLog(@"dic = %@",dic);
                    NSString *resultcode = [dic objectForKey:@"ResultCode"];
                    if (resultcode && resultcode.intValue == 0) {
                         //不需要
                         _imagedealcodeTF.placeholder = @"本次无需图形验证码";
                         _imagedealcodeTF.enabled = NO;
                         _imagedealcodeBtn.hidden = YES;
                         _dealcodeimageView.hidden = YES;
                         
                         
                    }if (resultcode && resultcode.intValue == 1) {
                         //需要
                         
                    }
                    
                    
               }];
               
               
               
               
          }
          
          
          
     }];
}

-(NSString *)createPostBody:(NSDictionary *)params

{
     NSString *postString=@"";
     for(NSString *key in [params allKeys])
     {
          NSString *value= [params objectForKey:key];
          postString =[postString stringByAppendingFormat:@"%@=%@&",key,value];
     }
     if([postString length] > 1)
     {
          postString=[postString substringToIndex:[postString length]-1];
     }
     return postString;
}




- (IBAction)getdealcodeClick:(id)sender {
     
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请先输入手机号");
          return;
     }
     //     [self loadstatues];
     NSDictionary *param = @{@"m":@"sendrandompwd",@"phone":_phoneTF.text};
     
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://login.189.cn/login/ajax"]];
     NSString *post =  [self createPostBody:param];
     NSLog(@"post = %@",post);
     
     [request setHTTPMethod:@"POST"];
     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
     [request setHTTPBody:postData];
     [request setTimeoutInterval:60.0];
     
     
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
          NSString *jsonstr = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
          NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
          NSLog(@"dic = %@",dic);
          NSString *result = [dic objectForKey:@"ResultCode"];
          if (result && result.intValue == 0) {
               //成功
               NSLog(@"发送成功！");
               [self countdown:sender];
          }else{
               NSLog(@"发送失败！");
          }
          
     }];
     
}

/**
 *  倒计时
 */

- (void)countdown:(UIButton *)btn {
     self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
     
     CYWeakObject(weakself, self);
     __block int time = 119;
     [self.GCDTimer event:^{
          if (time < 1) {
               //设置界面的按钮显示 根据自己需求设置
               [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
               btn.userInteractionEnabled = YES;
               //            btn.backgroundColor = CYColor(79, 118, 245, 1);
               [weakself.GCDTimer destroy];
          } else {
               //        NSLog(@"time:%d", time);
               [btn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
               btn.userInteractionEnabled = NO;
               //            btn.backgroundColor = CYColor(211, 211, 211, 1);
          }
          time--;
     } timeInterval:NSEC_PER_SEC * 1];
     [self.GCDTimer start];
}

- (IBAction)imagedealcodeClick:(id)sender {
}
- (IBAction)yanzhengClick:(id)sender {
}

-(void)submitclick{
     //登录
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请先输入手机号");
          return;
     }
     if (_dealcodeTF.text.length==0) {
          CYAlertView(@"请填写验证码");
          return;
     }
     if (!_ProvinceID) {
          _ProvinceID = @"";
     }if (!_AreaCode) {
          _AreaCode = @"";
     }if (!_CityNo) {
          _CityNo = @"";
     }

     NSString *pwd = [_webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"aesEncrypt('%@')",_dealcodeTF.text]];
     //     CYLog(@"pwd = %@",pwd);
     NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://login.189.cn/login"]];
     NSDictionary *dic = @{@"Account":_phoneTF.text,@"UType":@"201",@"ProvinceID":_ProvinceID,@"AreaCode":_AreaCode,@"CityNo":_CityNo,@"RandomFlag":@"1",@"Password":pwd,@"Captcha":@""};
     NSString *post =  [self createPostBody:dic];
     NSLog(@"post = %@",post);
     
     //    {
     //        Account = 13354985521;
     //        AreaCode = "";
     //        Captcha = "";
     //        CityNo = "";
     //        Password = "iWrQk/+molo8tlb4BZEc1g==";
     //        ProvinceID = "";
     //        RandomFlag = 1;
     //        UType = 201;
     //    }
     //    CityNo=&ProvinceID=&UType=201&Account=13354985521&AreaCode=&RandomFlag=1&Password=iWrQk/+molo8tlb4BZEc1g==&Captcha=
     
     [mutableRequest setHTTPMethod:@"POST"];
     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
     [mutableRequest setHTTPBody:postData];
     [mutableRequest setTimeoutInterval:60.0];
     
     NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:mutableRequest delegate:self];
     [connection start];
     
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
     NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
     NSDictionary *fields = [HTTPResponse allHeaderFields];
     NSLog(@"fields = %@",[fields description]);
     NSLog(@"================================================");
     NSLog(@"will send request\n%@", [request URL]);
     NSLog(@"redirect response\n%@", [response URL]);
     NSString *redURL = [fields objectForKey:@"Location"];
     
     CYLog(@"redURL = %@",redURL);
     
     if (redURL && [redURL hasPrefix:@"http://www.189.cn/login/ecs.do"]) {
//          _longstr = redURL;
//          [self correntlogin];
          [self loaddata];
          
          NSMutableURLRequest *requestRed = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redURL]];
          requestRed.allHTTPHeaderFields = [HTTPResponse allHeaderFields];
          return requestRed;
     }
     return request;
}
-(void)correntlogin{
     //拆解数组
     CYLog(@"loginurl = %@",_longstr);
     // redURL = http://www.189.cn/login/ecs.do?PlatNO=90000&ResultCode=0&Ticket=900002409554f30b94e4982e434fb3ef2aaf00e9d02b&TxID=9000051214c323f8f4833a6d7b42d67f484aa
     
     NSArray  *longarray= [_longstr componentsSeparatedByString:@"?"];
     NSString *urlstr = [longarray objectAtIndex:0];
     
     NSDictionary *params = [CYTool getURLParameter:_longstr];
     CYLog(@"params = %@",params);
      [CYHttpTool postWithURL:urlstr params:params success:^(id json) {
           NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          //
          CYLog(@"success?");
          [self loaddata];
          
     } failure:^(NSError *error) {
          
     }];

     
     
}

//- (void)connection:(NSURLConnection __unused *)connection
//didReceiveResponse:(NSURLResponse *)response
//{
//     NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
//     NSDictionary *fields = [HTTPResponse allHeaderFields];
//     NSLog(@"fields2 = %@",[fields description]);
//     
//}
//
//- (void)connection:(NSURLConnection __unused *)connection
//    didReceiveData:(NSData *)data
//{
//     NSString *jsonstr = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
////     NSLog(@"jsonstr = %@",jsonstr);
//     [self loaddata];
//}


-(void)loaddata{
     //     访问产品页成功，获取资料
     
     
     //    NSDictionary *param = @{@"m":@"sendrandompwd",@"phone":_phoneTF.text};
     
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://yn.189.cn/service/manage/my_selfinfo.jsp"]];
     [request setHTTPMethod:@"POST"];
     //    NSData *postData = [[param jk_JSONString] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
     //    [request setHTTPBody:postData];
     [request setTimeoutInterval:10.0];
     
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
          NSString *jsonstr = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
          CYLog(@"jsonstr = %@",jsonstr);
//          NSLog(@"jsonstr = %@",jsonstr);
          
     }];
     
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
